<template>
  <!-- 购买确认弹窗 -->
  <el-dialog v-model="payDialogVisible" title="确认购买" @close="resetDialog" width="35vw" center>
    <p>商品名称: {{ selectedProduct?.name }}</p>
    <p>商品简介: {{ selectedProduct?.info }}</p>
    <p>价格: {{ selectedProduct?.price }} 曼波币</p>
    <p>库存: {{ selectedProduct?.num }}</p>

    <div class="quantity-selector">
      <el-input-number v-model="quantity" :min="1" :max="maxQuantity" label="购买数量" />
      <p>单次最多可购买 {{ maxQuantity }} 件</p>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="resetDialog">取消</el-button>
      <el-button type="primary" @click="confirmPurchase">确认购买</el-button>
    </span>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineEmits } from 'vue';
import axios from 'axios';
import { defineProps } from 'vue';
import productPay from '../../order_detail/index.vue';
import router from '@/router';
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
interface ProductItem {
  id: number;              // 映射到后端的id字段
  name: string;            // 商品名称
  info: string;            // 商品简介
  price: string;           // 商品价格
  num: number;             // 库存数量
  limitNum: number;        // 单次最大购买数量
  bossId: number;          // 商家ID
}

// 接收商品数据作为 props
const props = defineProps<{
  item: ProductItem;  // 使用 ProductItem 作为 item 的类型
  isShow: boolean;
}>();
const emits = defineEmits(['close'])
const payDialogVisible = ref(false);  // 控制弹窗显示/隐藏
const selectedProduct = ref<ProductItem | null>(null);  // 存储选中的商品
const quantity = ref(1);  // 购买数量
const maxQuantity = ref(0);  // 单次最大购买数量

watch(() => props.isShow, (newIsShow) => {
  if (newIsShow) {
    openPayDialog(props.item);
  }
});

const openPayDialog = (product: ProductItem) => {
  selectedProduct.value = product;
  maxQuantity.value = Math.min(product.num, product.limitNum); // 最大购买数量
  quantity.value = 1; // 默认购买数量为1
  payDialogVisible.value = true;
};
const orderData = ref(<{
  addressId: number;
  bossId: number;
  coins: number;
  createdAt: string;
  id: number;
  num: number;
  orderNum: string;
  productId: number;
  type: number;
  updatedAt: string;
  userId: number;
}>{})
const orderToken = ref('')
const confirmPurchase = () => {
  if (!selectedProduct.value) return;

  const Data = {
    productId: selectedProduct.value.id,
    userId: userStore.userInfo.id, 
    bossId: selectedProduct.value.bossId,
    quantity: quantity.value
  };

  axios.post('/api/orders/create', Data)
    .then((response) => {
      if (response.data.code === 200) {
        console.log('订单创建成功！', response.data.data);

        
        
        resetDialog(); // 关闭弹窗
        // orderData.value = response.data.data.order
        // orderToken.value = response.data.data.payToken
        // router.push(`/order_detail/${orderData.value.id}`);
        
      } else {
        alert('订单创建失败，请稍后重试');
      }
    })
    .catch((error) => {
      console.error('订单创建请求失败:', error);
      alert('订单创建失败，请稍后重试');
    });
};

const resetDialog = () => {
  payDialogVisible.value = false;
  selectedProduct.value = null;
  quantity.value = 1; // 重置数量
  emits('close')
};

onMounted(() => {
  console.log('props.item:', props.item);
});
</script>
